<?php

	/**
     * Event compiler
     *
	 * @package      Core
	 * @subpackage   Event
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
	 */
	class Core_Event_Compiler
    {

	////////////////////////////////////////////////////////////////////////////
	//                             Static Methods                             //
	////////////////////////////////////////////////////////////////////////////


        /**
         * Retrieves the event's XML content from the modules.
         * It stores the result in a temporary file
         *
         * @return      array
         */
        public static function get()
        {
            $eventList      = array();
            $registry       = Zend_Registry::getInstance();
            $cachefile      = Core_IO_Path::combine(PROJECT_TEMP_PATH, 'compiled', '~events~');
            $mustCompile    = $registry['config']->compilation->force || !Core_IO_File::exists($cachefile);

            if (!$mustCompile) {
                foreach ($registry['modules'] as $module) {
                    $file = Core_IO_Path::combine($module, 'events.xml');

                    if (Core_IO_File::exists($file)) {
                        if (@filemtime($file) > @filemtime($cachefile)) {
                            $mustCompile = true;
                        }
                    }
                }
            }

            if ($mustCompile) {
                foreach ($registry['modules'] as $module => $path) {
                    $file = Core_IO_Path::combine($path, 'events.xml');

                    if (@is_readable($file)) {
                        $xml = @simplexml_load_file($file);

                        if (isset($xml->listener)) {
                            foreach ($xml->listener as $listener) {
                                $listenerName = (string)$listener['name'];

                                foreach ($listener->event as $eventListened) {
                                    $name = (string)$eventListened['name'];

                                    // key: event's name, value: listener files
                                    $eventList[$name][] = array($module, $listenerName);
                                }
                            }
                        }

                        unset($xml);
                    }
                }

                Core_IO_File::writeAll($cachefile, var_export($eventList, true));
            } else {
                $str = Core_IO_File::readAll($cachefile);
                $eventList = eval('return '. $str .';');
            }

            return $eventList;
        }
    }
